var express = require('express');
var router = express.Router();

// 引入数据库
const DB = require("../utils/db")

// 公共的数据应该别提炼出来，并且封装成一个模块
// let api_url="http://localhost:3000"
const  {api_url}=require("../utils/config")




/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express11' });
});




// 首页的banners路由(获取轮播图的图片地址和标题)
router.get("/banners", async (req, res, next) => {

  // let sql = `select  *  from  e_banners where isshow=1`

  // let sql=`select  CONCAT("http://localhost:3000/uploads/",image_src)  from  e_banners where isshow=1`

  let sql=`select id,
                  title, 
                  CONCAT("${api_url}","/uploads/",image_src)  as image_src
                  from  e_banners 
                  where isshow=1`


  let [err, result] = await DB(sql)
  // console.log([err,result]);


  // 错误拦截
  if (err) {
    next("banners请求失败")
    return
  }



  // 把最终结果响应出去
  res.send({
    status: 200,
    msg: "banners请求成功",
    result

  })
})


// 同步和精品
router.get("/courses", async (req,res,next)=>{
    // 接收参数：type   只能是1（默认 同步）2精品
    let  {type=1}=req.query



    // 根据参数，查询数据库 
    let sql=`select id,
                    cid,
                    title,
                    price,
                    CONCAT("${api_url}","/uploads/","course/",image_src)  as image_src,
                    type, 
                    type_name,
                    area_name,
                    subject_name
             from e_course 
             where status!=4 
             and type=${type}
             limit 12`
    let [err,result]=await DB(sql)
    // console.log(err);
    // res.send(result)


    if(err){
      next(type==1?"同步"+"课程请求成功":"精品" +"课程请求失败")
      return
    }


    res.send({
      status:200,
      msg:type==1?"同步"+"课程请求成功":"精品" +"课程请求成功",
      result
    })

})




module.exports = router;
